﻿<template>
  <el-dialog v-drag title = '查看运行结果' :visible.sync = 'dialogVisible' width = "60%"
  append-to-body  class = 'main_dialog' @close = "closeDialog">
    <div v-if = 'showReusltDialog' v-loading = 'loading' element-loading-text = '数据加载中...'>
      <link href = '/static/editorJson/all.min.css' rel = 'stylesheet'>
      <link href = '/static/editorJson/jsoneditor.min.css' rel = 'stylesheet'>
      <div id = 'json_editor' class = 'editarea'></div>
    </div>
  </el-dialog>
</template>

<script>
import scriptjs from 'scriptjs'
export default {
  props: ['showReusltDialog', 'defaultValue'],
  data () {
    return {
      dialogVisible: false,
      loading: false,
      editorJson: null,
      currentValue: ''
    }
  },
  methods: {
    fetchScript: function (url) {
      return new Promise((resolve) => {
        scriptjs(url, () => {
          resolve()
        })
      })
    },
    // 初始化页面的方法
    initPage: async function () {
      let _self = this
      _self.editorJson = null
      _self.currentValue = _self.defaultValue ? decodeURIComponent(_self.defaultValue) : ''
      _self.loading = true
      await this.fetchScript('/static/editorJson/jsoneditor.min.js')
      _self.$nextTick(() => {
        _self.editorJson = new window.JSONEditor(document.getElementById('json_editor'), { mode: 'code' })
        setTimeout(() => {
          _self.editorJson.setText(_self.currentValue)
          _self.loading = false
        }, 1000)
        document.getElementsByClassName('jsoneditor-format')[0].setAttribute('title', '格式化')
        document.getElementsByClassName('jsoneditor-compact')[0].setAttribute('title', '序列化')
        document.getElementsByClassName('jsoneditor-repair')[0].setAttribute('title', '修正json格式')
      })
    },
    closeDialog () {
      this.$emit('closeResultDialog')
    }
  },
  watch: {
    // 弹窗打开的方法
    showReusltDialog: {
      handler: function (val, oldVal) {
        this.dialogVisible = val
        if (val) {
          this.initPage()
        } else {
          if (this.editorJson) {
            this.editorJson.destroy()
            this.editorJson = null
          }
        }
      },
      deep: true
    }
  }
}
</script>

<style lang = 'scss'>
#json_editor {
  height: 660px;
  .jsoneditor-sort,
  .jsoneditor-transform,
  .jsoneditor-poweredBy {
    display: none !important;
  }
  .jsoneditor-menu {
    button {
      opacity: 1;
    }
  }
}
#showJson {
  max-height: 700px;
}
@media (max-width:1367px) {
  #json_editor {
    height: 400px;
  }
  #showJson {
    max-height: 450px;
  }
}
</style>
